package com.wangyh.edit.prettyedit.html;

import com.wangyh.edit.prettyedit.constant.EditConstant;
import com.wangyh.edit.prettyedit.pages.IPageService;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.InputMethodEvent;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.fxmisc.flowless.VirtualizedScrollPane;
import org.fxmisc.richtext.CodeArea;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 用户个人中心页面
 * @author wangyh
 *
 */
public class EditHtmlPage implements IPageService {

    @Override
    public Node generatePageToRoot(Pane root) {
//        VBox vbox = new VBox();
//        vbox.setAlignment(Pos.CENTER);
//        TextArea test = new TextArea("个人中心页面");
////        StyleUtil.setFont(test, Color.BLACK, 20);
//        vbox.getChildren().add(test);
//
//        root.getChildren().add(vbox);
        return root;
    }

    @Override
    public Node generatePage(String[] args) {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/views/TextEditorView.fxml"));
        //根节点
        AnchorPane anchorPane = null;
        try {
            anchorPane = loader.load();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//        anchorPane.setStyle("-fx-border-color: #ff0000; -fx-border-radius: 3");

        //创建HTML富文本编辑器对象
        HTMLEditor htmlEditor = new HTMLEditor();
        anchorPane.getChildren().add(htmlEditor);
        //设置位置
        anchorPane.setLeftAnchor(htmlEditor, 0.0);
        anchorPane.setRightAnchor(htmlEditor, 0.0);
        anchorPane.setBottomAnchor(htmlEditor, 0.0);
        anchorPane.setTopAnchor(htmlEditor, 0.0);

//        htmlEditor.prefWidthProperty().bind(anchorPane.widthProperty());
//        htmlEditor.prefHeightProperty().bind(anchorPane.heightProperty());

        //文件
        File file = new File(args[0]);

//        htmlEditor.setPrefHeight(100);
//        htmlEditor.addEventHandler(new );
//        htmlEditor.setStyle("-fx-border-color: #00ff00; -fx-border-radius: 3");

        htmlEditor.setOnKeyReleased(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                //设置名字 , 加 *
//                Stage stage = (Stage) htmlEditor.getParent().getScene().getWindow();
//                stage.setTitle(EditConstant.appName + "   //-> " + file.getName() + " *");

                //直接保存
                String str = htmlEditor.getHtmlText();
                FileWriter fw = null;
                try {
                    fw = new FileWriter(file.getAbsolutePath(), Charset.forName("utf-8"));
                    fw.write(str);
                    fw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file, Charset.forName("utf-8")));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(s + System.lineSeparator());
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        if(result.toString().trim().length()==0){
            //设置内容
            htmlEditor.setHtmlText("");
        }else {
            //设置内容
            htmlEditor.setHtmlText(result.toString());
        }

        //构造菜单事件
        generateMenu();

        return anchorPane;
    }

    /**
     * 构造菜单事件
     */
    private void generateMenu(){
        //获取菜单
        MenuBar menuBar = (MenuBar) EditConstant.mainFrameView.getSceneRoot().getTop();
        Menu menu = menuBar.getMenus().get(1);
        MenuItem saveMenu = menu.getItems().get(0);
        saveMenu.setDisable(false);

        saveMenu.setOnAction(
                new EventHandler<ActionEvent>() {
                    public void handle(ActionEvent event) {
                        //保存
                        BorderPane borderPane = (BorderPane) menuBar.getScene().getRoot();
                        TreeView<File> treeView = (TreeView) borderPane.getLeft();
                        TreeItem<File> selectedItem = treeView.getSelectionModel().getSelectedItem();
                        if(selectedItem!=null && selectedItem.getValue().getName().endsWith("html")){
                            System.out.println(selectedItem.getValue().getName());
                            System.out.println(selectedItem.getValue().getAbsolutePath());

                            Node node = borderPane.getCenter();
                            System.out.println(node);
                            if(node instanceof AnchorPane){
                                HTMLEditor sp = (HTMLEditor) ((AnchorPane) node).getChildren().get(0);
                                String str = sp.getHtmlText();

                                FileWriter fw = null;
                                try {
                                    fw = new FileWriter(selectedItem.getValue().getAbsolutePath(), Charset.forName("utf-8"));
                                    fw.write(str);
                                    fw.close();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }else{
                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setContentText("当前无编辑的文档，请编辑后进行保存！");
                                alert.setTitle("保存失败！");
                                alert.setHeaderText("保存失败！");
                                alert.show();
                            }

                            //设置名字 , 去掉 *
                            Stage stage = (Stage) menuBar.getScene().getWindow();
                            stage.setTitle(EditConstant.appName + "   //-> " + selectedItem.getValue().getName());
                        }else{
                            Alert alert = new Alert(Alert.AlertType.INFORMATION);
                            alert.setContentText("当前无编辑的文档，请编辑后进行保存！");
                            alert.setTitle("保存失败！");
                            alert.setHeaderText("保存失败！");
                            alert.show();
                        }

                    }
                }
        );

        //保存html
        MenuItem menuItem42 = menu.getItems().get(2);
        menuItem42.setDisable(false);
        menuItem42.setOnAction(
                new EventHandler<ActionEvent>() {
                    public void handle(ActionEvent event) {
                        FileChooser fileChooser = new FileChooser();
                        fileChooser.setTitle("另存为html");
                        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("html", "*.html"));
                        File file = fileChooser.showSaveDialog(new Stage());
                        if (file != null) {
                            //保存
                            BorderPane borderPane = (BorderPane) menuBar.getScene().getRoot();
                            TreeView<File> treeView = (TreeView) borderPane.getLeft();
                            TreeItem<File> selectedItem = treeView.getSelectionModel().getSelectedItem();
                            if (selectedItem != null && selectedItem.getValue().getName().endsWith("html")) {
                                System.out.println(selectedItem.getValue().getName());
                                System.out.println(selectedItem.getValue().getAbsolutePath());

                                Node node = borderPane.getCenter();
                                System.out.println(node);
                                if(node instanceof AnchorPane){
                                    HTMLEditor sp = (HTMLEditor) ((AnchorPane) node).getChildren().get(0);
                                    String str = sp.getHtmlText();

                                    FileWriter fw = null;
                                    try {
                                        fw = new FileWriter(file, Charset.forName("utf-8"));
                                        fw.write(str);
                                        fw.close();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                } else {
                                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                    alert.setContentText("当前无编辑的文档，请编辑后进行另存！");
                                    alert.setTitle("保存失败！");
                                    alert.setHeaderText("保存失败！");
                                    alert.show();
                                }
                            } else {
                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setContentText("当前无编辑的文档，请编辑后进行另存！");
                                alert.setTitle("保存失败！");
                                alert.setHeaderText("保存失败！");
                                alert.show();
                            }
                        }
                    }
                }
        );


    }

}
